package com.cl.cloud.common.util;

import java.text.DecimalFormat;

/**
 * @description:
 * @author: liuzijian
 * @time: 2022-03-03 17:54
 */
public class NumToRmbUtil {
    private static String[] hanArr = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾"};
    private static String[] unitArr = {"圜", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "拾", "佰", "仟", "兆", "拾"};

    public static String toHanStr(double numStr) {
        String result = "";
        DecimalFormat format = new DecimalFormat("#.00");
        String num = format.format(numStr);
        System.out.print(num);
        int bit = num.indexOf('.');
        String total = num.substring(0, bit);
        result += totleStr(total);
        if (bit == num.length() - 1) {
            result += "整";
        } else {
            String other = num.substring(bit + 1, num.length());
            result += otherStr(other);
        }
        return result;
    }

    public static String otherStr(String num) {
        String result = "";
        char jiao = num.charAt(0);
        char fen = num.charAt(1);
        if (jiao == '0' && fen == '0') {
            result += "整";
        }
        if (jiao != '0') {
            result += (hanArr[jiao - '0'] + "角");
        }
        if (fen != '0') {
            result += (hanArr[fen - '0'] + "分");
        }
        return result;
    }

    public static String totleStr(String num) {
        //String num = String.valueOf(numStr);
        int numLen = num.length();
        String result = "";
        for (int i = 0; i < numLen; i++) {
            int numtemp = num.charAt(i) - '0';
            if (numtemp != 0 && (numLen - 1 - i) % 4 != 0) {
                result += (hanArr[numtemp] + unitArr[numLen - 1 - i]);
            } else {
                if (numtemp != 0) {
                    result += (hanArr[numtemp]);
                } else {
                    int low = ((numLen - 1 - i) / 4) * 4;//每级的最低位
                    int lowbit = numLen - low - 1;

                    //判断是不是每级末尾的连续零，如果是的话，这个零不读
                    boolean all_zero = true;
                    for (int j = i; j <= lowbit; j++) {
                        if ((num.charAt(j) - '0') != 0) {
                            all_zero = false;
                            break;
                        }
                    }

                    //判断是不是连零，只读下一位的数字不是零的，那一个零
                    if (!all_zero && (numLen - 1 - i) % 4 != 0) {
                        if ((num.charAt(i + 1) - '0') != 0) {
                            result += (hanArr[numtemp]);
                        }
                    }
                }

                if ((numLen - 1 - i) % 4 == 0) {
                    result += (unitArr[numLen - 1 - i]);
                }
            }
        }
        return result;
    }
}
